package com.example.administrator.yunan1;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.nle.mylibrary.forUse.zigbee.FourChannelValConvert;
import com.nle.mylibrary.forUse.zigbee.Zigbee;
import com.nle.mylibrary.transfer.DataBusFactory;

public class MainActivity extends AppCompatActivity {
    private ToggleButton btn_1;
    private TextView tv_temp;
    private TextView tv_shi;
    private Zigbee zigbee;
    private Boolean flag=false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();

        btn_1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(btn_1.isChecked()){
                    zigbee = new Zigbee(DataBusFactory.newSocketDataBus("172.18.14.200", 4196));
                    flag=true;
                    Log.i("flag",flag+"");
                    Mythread mythread=new Mythread();
                    mythread.start();
                }else {
                    zigbee.stopConnect();
                    flag=false;
                    Log.i("flag",flag+"");

                }
            }
        });

    }
    private  void init(){
        btn_1=findViewById(R.id.btn_1);
        tv_temp=findViewById(R.id.tv_temp);
        tv_shi=findViewById(R.id.tv_shi);


    }
    private class Mythread extends Thread{
        @Override
        public void run() {
            super.run();

            while (flag){
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                try {
                    double[] val = zigbee.getFourEnter();
                    final double temperature = FourChannelValConvert.getTemperature(val[0]);
                    final double shi = FourChannelValConvert.getHumidity(val[1]);
                    Log.i("temperature",temperature+"");
                    Log.i("shi",shi+"");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            tv_temp.setText(temperature+"°");
                            tv_shi.setText(shi+"RH");
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
